var companyId=$("#companyId").val();
var $newMemberTaable=$("#newMember");

$(function () {
    $('.datepicker').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    meberData(companyId)
    ajaxData(companyId)
    customerIntentionInit()
})

function timeSelectTop(th,type) {
    $(th).addClass('active-second')
    $(th).siblings().removeClass('active-second')
    $("#dateTypeTop").val(type)
    if(type==''){
        // if(){}
        // $('#customInput').css('display','block');
        if($("#customInputTop").is(":hidden")){
            $('#customInputTop').show();
        }else{
            $('#customInputTop').hide();
        }

    }else{
        // $('#customInput').css('display','none');
        $('#customInputTop').hide();

        $('#startTmTop').val('');
        $('#startTmTop').val('');
        meberData(companyId)
        ajaxData(companyId)

    }


}

$("#customDateBtnTop").on('click',function () {
    meberData(companyId)
    ajaxData(companyId)
})

function meberData(type){
    $.ajax({
        type: 'post',
        url: 'https://mgapi.dcrm.cn/call/selectListByCompangyId',
        //url: 'http://127.0.0.1:8087/call/selectListByCompangyId',
        dataType: "json",
        // contentType: "application/json;charset=utf-8",
        data: {
            companyId : type,
            dateType:$("#dateTypeTop").val(),
            arriveTimeStart:$("#startTmTop").val(),
            arriveTimeEnd:$("#endTmTop").val(),
        },
        success: function (result) {
            // console.log(result,'result')


            let _xname=result.name;
            let _ydata1=result.data1;
            let _ydata2=result.data2;
            let _ydata3=result.data3;
            let _ydata4=result.data4;



            if(_xname.length!=0){
                echartClientRate('talkTime',_xname,_ydata1,_ydata2,_ydata3,_ydata4,'','60s以内','60-90s','60s以上','90s以上')
            }else{
                // $("#talkTime").text('暂无数据')
                document.getElementById('talkTime').innerHTML='暂无数据'
                document.getElementById('talkTime').removeAttribute('_echarts_instance_')
            }


            if(result.code == '000000') {
            }
        },
        error: function(){
            // alert('请求失败')
            $.alert('请求失败')
        }
    });
}

function echartClientRate(id,xdata,ydata1,ydata2,ydata3,ydata4,title_text,y_name1,y_name2,y_name3,y_name4) {
    //客户分析转化表
    let clientRate=document.getElementById(id)
    let myChart = echarts.init(clientRate);
    line_option.xAxis[0].data = xdata
    line_option.series[0].data = ydata1
    //
    line_option.series[1].data = ydata2
    line_option.series[2].data = ydata3
    line_option.series[3].data = ydata4
    line_option.title.text=title_text
    line_option.series[0].name = y_name1
    line_option.series[1].name = y_name2
    line_option.series[2].name = y_name3
    line_option.series[3].name = y_name4
    if(xdata.length>10){
        line_option.dataZoom=[    {
            type: 'slider',
            show: true,
            start:94,
            end: 100,
            handleSize: '100%',
            realtime: true,
        },
        {
            type: 'inside',
            start: 0,
            end: 100
        }]
    }else{
        line_option.dataZoom=[]
    }

    let dataMax=[];
    dataMax=dataMax.concat(ydata1,ydata2,ydata3,ydata4)
    if(Math.max.apply(null, dataMax),Math.max.apply(null, dataMax).toString().length==2){
        line_option.yAxis[0].interval=20
    }else if(Math.max.apply(null, dataMax),Math.max.apply(null, dataMax).toString().length==3){
        line_option.yAxis[0].interval=50
    }else if(Math.max.apply(null, dataMax),Math.max.apply(null, dataMax).toString().length==4){
        line_option.yAxis[0].interval=100
    }
    // line_option.yAxis[0].interval=Math.max.apply(null, dataMax)

    // console.log(ydata1,dataMax,'dataMax',Math.max.apply(null, dataMax),Math.max.apply(null, dataMax).toString().length)



    myChart.setOption(line_option);
    // window.onresize = myChart.resize;
    window.addEventListener('resize',()=>{
        myChart.resize()
    })
    /**/
}

const color = ['#6699ff',"#52cca3", '#caed8b']
var line_option={
    title: {
        text: '通话统计',
        left: '5%',
        top: '3%',
        textStyle: {
            color: '#999999',
            fontSize: '12',
        },
    },
    legend: {
        left: 'center',
        top: '30',
        data: ['60s以内', '60-90s', '60s以上','90s以上']
    },
    dataZoom :[

    ],
    tooltip: {
        trigger: 'axis',
        /*formatter: function (params) {
            var html = '<div class="tooltip-box">';
            html += params[0].axisValue + '<br>';
            html += '<span class="tooltip-icon tips-1"></span>' + params[0].seriesName + ': ' + parseInt(params[0].data * 100) + '%<br>';
            html += '<span class="tooltip-icon tips-2"></span>' + params[1].seriesName + ': ' + params[1].data + '<br>';
            html += '<span class="tooltip-icon tips-3"></span>' + params[2].seriesName + ': ' + params[2].data + '</div>';
            return html;
        }*/
    },
    grid: {
        x: '3%',
        x2: '4%',
        y: '95',
        y2: '50',
        containLabel: true
    },
    xAxis: [{
        show: true,
        type: 'category',
        axisLine: {
            show: true,
            lineStyle:{
                color:'rgba(83, 83, 83,0.1)',
            },
        },
        axisPointer: {
            type: 'shadow'
        },
        axisTick:{//坐标轴刻度相关设置。
            show: false,
        },
        axisLabel: {
            color: '#999999',
            margin:20
        },
        splitLine: {
            show: false
        },
        boundaryGap: true,
        data: [],

    }],
    yAxis: [
        {
            type: 'value',
            name:'',
            interval: 20,
            nameTextStyle: {
                padding: [0, 13, 6, 0],
                align: 'right',
                color: '#333',
            },
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(83, 83, 83,0.1)'
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#999',
                    padding: [0, 6, 0, 0]
                }
            },
            splitArea: {
                areaStyle: {
                    color: 'rgba(255,255,255,.5)'
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#eee',
                    width: 1,
                    type: 'dashed'
                }
            }
        },

    ],
    series: [
        {
            name: "60s以内",
            type: "bar",
            // stack: "总量",
            barMaxWidth: 20,
            itemStyle: {
                normal: {
                    color:
                        {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: 'rgba(35, 157, 255, 1)' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: 'rgba(35, 157, 250, .5)' // 100% 处的颜色
                            }],
                            global: false // 缺省为 false
                        }
                }
            },
            data: []
        },
        {
            name: "60-90s",
            type: "bar",
            // stack: "总量",
            barMaxWidth: 20,
            itemStyle: {
                normal: {
                    color:
                        {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: 'rgba(241, 68, 108, 1)' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: 'rgba(241, 68, 108, .5)' // 100% 处的颜色
                            }],
                            global: false // 缺省为 false
                        }
                }
            },
            data: []
        },
        {
            name: "60s以上",
            type: "bar",
            // stack: "总量",
            barMaxWidth: 20,
            itemStyle: {
                normal: {
                    color:
                        {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: 'rgba(135, 241, 68, 1)' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: 'rgba(135, 241, 68, .5)' // 100% 处的颜色
                            }],
                            global: false // 缺省为 false
                        }
                }
            },
            data: []
        }, {
            name: "90s以上",
            type: "bar",
            // stack: "总量",
            barMaxWidth: 20,
            itemStyle: {
                normal: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: 'rgba(128, 30, 234, 1)' // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: 'rgba(128, 30, 234, .5)' // 100% 处的颜色
                        }],
                        global: false // 缺省为 false
                    },
                    barBorderRadius: 0
                },
            },
            data: []
        },
    ]
};


function ajaxData(type) {
    $.ajax({
        type: 'post',
        url: 'https://mgapi.dcrm.cn/call/selectList',
        //url: 'http://127.0.0.1:8087/call/selectList',
        dataType: "json",
        // contentType: "application/json;charset=utf-8",
        data: {
            companyId : type,
            dateType:$("#dateTypeTop").val(),
            arriveTimeStart:$("#startTmTop").val(),
            arriveTimeEnd:$("#endTmTop").val(),
        },
        success: function (result) {

            // console.log(result,'result')

            let flag=false
            for(let i=0,len=result.length;i<len;i++){
                if(result[i].value!=0){
                    flag=true
                }
            }
            if(flag){
                memberPercentageInit('talkTimePercentage',result)
            }
            else{
                // $("#talkTimePercentage").html('暂无数据')
                document.getElementById('talkTimePercentage').innerHTML='暂无数据'
                document.getElementById('talkTimePercentage').removeAttribute('_echarts_instance_')
            }


            if(result.code == '000000') {
            }
        },
        error: function(){
            // alert('请求失败')
            $.alert('请求失败')
        }
    });
}


function memberPercentageInit(id,data){
    let memberdom = document.getElementById(id);
    let memberChart = echarts.init(memberdom);
    let option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {

            left: 'center'
        },
        color : ['#6699FF', '#52CCA3', '#B3CDFF'],
        series: [
            {
                name: '时长',
                type: 'pie',
                radius: '70%',
                // data: [
                //     // {value: data.memberQuota, name: '60s以内'},
                //     // {value: data.renewMemberQuota, name: '60-90s'},
                //     // {value: data.noMemberQuota, name: '90s以上'},
                // ],
                data: data,
                label: {
                    show: false,
                    position: 'inner',
                },
                emphasis: {
                    itemStyle: {
                        // shadowBlur: 10,
                        // shadowOffsetX: 2,
                        // shadowColor: 'rgba(255, 255, 255, 1)'
                        borderColor: '#fff',
                        borderWidth: 4
                    }
                }
            }
        ]
    };
    memberChart.setOption(option);
    window.addEventListener("resize",function(){
        memberChart.resize();
    });
}


function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.companyId=$("#companyId").val()
    params.dateType=$("#dateType").val()
    params.arriveTimeStart=$("#startTm").val()
    params.arriveTimeEnd=$("#endTm").val()
    return params;
}

function customerIntentionInit(){
    //先销毁表格
    $newMemberTaable.bootstrapTable('destroy');
    $newMemberTaable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: 'https://mgapi.dcrm.cn/call/selectCallOutPage',//请求地址
        //url: 'http://127.0.0.1:8087/call/selectCallOutPage',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'tatolHour',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        pageSize: 50,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[50,100]",//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'formId', visible: false},
            {title: '姓名', field: 'userName', align: 'left', valign: 'middle'},
            {title: '电话数量', field: 'tatolNumber', align: 'left', valign: 'middle'},
            {title: '60s以内', field: 'inSixSeconds', align: 'left', valign: 'middle'},
            {title: '60-90s', field: 'sixToNineSeconds', align: 'left', valign: 'middle'},
            {title: '60s以上', field: 'onSixSeconds', align: 'left', valign: 'middle'},
            {title: '90s以上', field: 'onNineSeconds', align: 'left', valign: 'middle'},
            {title: '总时长', field: 'tatolHour', align: 'left', valign: 'middle'}, //,sortable: true
            {title: '外出拜访量', field: 'bfCount', align: 'left', valign: 'middle'}, //,sortable: true
        ],
        responseHandler: function (result) {
            // if (result.code == "000000"){
            //     var obj = {
            //         "rows": result.data,
            //         "total": result.totalRecords
            //     };
            // } else {
            //     var obj = {
            //         "total": 0,
            //         "rows": [],
            //     }
            // }
            var obj = {
                "rows": result.list,

                "total": result.totalRecords,
            };
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

function timeSelect(th,type) {
    $(th).addClass('active-second')
    $(th).siblings().removeClass('active-second')
    $("#dateType").val(type)
    if(type==''){
        // if(){}
        // $('#customInput').css('display','block');
        if($("#customInput").is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }

    }else{
        // $('#customInput').css('display','none');
        $('#customInput').hide();
        $('#startTm').val('');
        $('#endTm').val('');
        $newMemberTaable.bootstrapTable('refresh');
    }


}

$("#customDateBtn").on('click',function () {
    $newMemberTaable.bootstrapTable('refresh');
})